package com.smart.community.gateway.config;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * 跨域配置
 * 
 * @author Wu.Liang
 * @since 2024-01-15
 * @updated 2025-01-30 - 修复CORS重复源问题，使用Set去重
 */
@Configuration
public class CorsConfig {
    
    /**
     * 配置跨域过滤器
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        
        // 使用Set确保源不重复，避免Access-Control-Allow-Origin重复值问题
        Set<String> allowedOrigins = new HashSet<>();
        allowedOrigins.add("http://localhost:3000"); // 前端开发地址
        allowedOrigins.add("http://localhost:3001"); // 前端开发地址（新增）
        allowedOrigins.add("http://localhost:8080"); // 前端生产地址
        
        // 设置允许的源
        config.setAllowedOrigins(new ArrayList<>(allowedOrigins));
        
        // 允许携带认证信息
        config.setAllowCredentials(true);
        
        // 允许的请求头
        config.addAllowedHeader("*");
        
        // 允许的请求方法
        config.addAllowedMethod("*");
        
        // 预检请求的有效期 - 增加到2小时，减少OPTIONS请求频率
        config.setMaxAge(7200L);
        
        // 允许暴露的响应头 - 包含用户信息相关头
        config.addExposedHeader("Authorization");
        config.addExposedHeader("X-User-Id");
        config.addExposedHeader("X-User-Name");
        config.addExposedHeader("X-User-Role");
        config.addExposedHeader("X-User-Type");
        config.addExposedHeader("X-Client-Type");
        config.addExposedHeader("X-Client-Version");
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        
        return new CorsWebFilter(source);
    }
} 